<template>
  <div class="mod-config">
    <!-- 查询条件 -->
    <div class="search-form search_form">
      <el-form :model="searchForm" size="mini" label-position="right" class="demo-form-inline" label-width="100px">
        <el-row :gutter="5">
          <el-col :span="3">
            <el-form-item label="部门名称：" prop="deptId">
              <el-select v-model="searchForm.deptId" placeholder="请选择部门" disabled
              >
                <el-option
                  v-for="item  in  deptList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <el-form-item label="人员编号：">
              <el-input v-model="searchForm.userId" placeholder="请输入人员编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="姓名：">
              <el-input v-model="searchForm.userName" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="状态：">
              <el-select v-model="searchForm.status" placeholder="请选择" filterable clearable>
                <el-option
                  v-for="item in optionsStates"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="7">
            <el-form-item label="时间范围：" prop="dateInterval">
              <el-date-picker v-model="searchForm.dateInterval" type="daterange" value-format="timestamp"
                              range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="3" style="text-align:center;">
            <el-button size="mini" type="primary" @click="searchBtn">查询</el-button>
            <el-button size="mini" @click="emptyClick">清空</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-col :span="8" style="text-align:left;margin-bottom: 10px;">
        <el-button v-hasPermi="['/permission/export']" size="mini" type="info" @click="exportForm"
                   :disabled="this.checkedArr.length <= 0">导出
        </el-button>
        <el-button v-hasPermi="['/permission/commit']" size="mini" type="success"
                   :disabled=this.checkSubmit() @click="submit()">提交
        </el-button>
        <el-button v-hasPermi="['/permission/appeal']" size="small" type="danger"
                   :disabled=this.checkAppealSubmit() @click="appealSubmit()">申诉
        </el-button>
        <el-button size="mini" type="warning" v-hasPermi="['/permission/scoring']" @click="batchHandleDafen"
                   :disabled="tableData.length == 0 || !(tableData[0].state == 0 || tableData[0].state == 2)">批量评分
        </el-button>
      </el-col>
    </div>
    <el-table
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
      :row-key="bindRowKeys"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        reserve-selection="reserve-selection"
        :selectable="selectable"
        width="50">
      </el-table-column>

      <el-table-column
        prop="deptName"
        header-align="center"
        align="center"
        label="部门名称"
      >
      </el-table-column>
      <el-table-column
        prop="userId"
        header-align="center"
        align="center"
        label="新人员编号"
        width="200"
      >
      </el-table-column>
      <el-table-column
        prop="userName"
        header-align="center"
        align="center"
        label="姓名"
        width="200">
      </el-table-column>
      <el-table-column
        prop="performancePoint"
        header-align="center"
        align="center"
        label="部门绩效考核系数"
        width="180">
      </el-table-column>
      <el-table-column
        prop="level"
        header-align="center"
        align="center"
        label="员工绩效等级"
        width="200">
        <template slot-scope="scope">
          <span style="color: #999999 ;font-weight:bold" v-if="scope.row.level === 1">A+</span>
          <span style="color: #999999 ;font-weight:bold" v-if="scope.row.level === 2">A</span>
          <span style="color: #999999 ;font-weight:bold" v-if="scope.row.level === 3">B+</span>
          <span style="color: #999999 ;font-weight:bold" v-if="scope.row.level === 4">B</span>
          <span style="color: #999999 ;font-weight:bold" v-if="scope.row.level === 5">B-</span>
          <span style="color: #999999 ;font-weight:bold" v-if="scope.row.level === 6">C</span>
          <span style="color: #999999 ;font-weight:bold" v-if="scope.row.level === 7">D</span>
        </template>

      </el-table-column>
      <el-table-column
        prop="state"
        header-align="center"
        align="center"
        label="状态"
        width="180">
        <template slot-scope="scope">
          <span style="color: #999999 ;font-weight:bold" v-if="scope.row.state === 0">未提交</span>
          <span style="color: #13ce66;font-weight:bold" v-if="scope.row.state === 1">已提交</span>
          <span style="color: #ff4949; font-weight:bold" v-if="scope.row.state === 2">已驳回</span>
          <span style="color: gold ;font-weight:bold" v-if="scope.row.state === 3">已申诉</span>
          <span style="color: aquamarine ;font-weight:bold" v-if="scope.row.state === 4">已同意</span>
        </template>
      </el-table-column>

      <el-table-column
        prop="reviewerDescribe"
        header-align="center"
        align="center"
        label="审核意见"
        width="180">
      </el-table-column>

      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        label="时间"
        width="200"
      >
        <template slot-scope="scope">
          {{ new Date(scope.row.createTime).toLocaleDateString().replaceAll('/', '-') }}
        </template>
      </el-table-column>
    </el-table>
    <div class="progress_lok_page">
      <page
        :hidden="tableData && tableData.length === 0"
        :total="total"
        :page.sync="page"
        :limit.sync="pageSize"
        @pagination="handlePageChange"
      />
    </div>

    <el-dialog
      :title="'申诉'"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form :model="sensuForm" :rules="sensuRule" ref="sensuForm" @keyup.enter.native="sensuFormSubmit()"
               label-width="80px">
        <el-form-item label="申诉人" prop="appealUser">
          <el-input v-model="sensuForm.appealUser" disabled></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactNumber" style="margin: 14px 0;">
          <el-input v-model="sensuForm.contactNumber" placeholder="请输入联系方式"></el-input>
        </el-form-item>

        <el-form-item label="申诉描述" prop="description">
          <el-input type="textarea" v-model="sensuForm.description" placeholder="请输入申诉描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="sensuFormSubmit()">提交</el-button>
        </span>
    </el-dialog>

    <el-dialog
      :title="'批量打分'"
      :close-on-click-modal="false"
      :visible.sync="batchDanfenVisible"
      class="dialog-custom"
      width="600">
      <el-table :data="tableList" border>
        <el-table-column property="userName" label="姓名" width="170" align="center"></el-table-column>
        <el-table-column property="level" label="打分" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-radio-group v-model="scope.row.level" @change="batchLevelChange($event,scope.row,scope.$index)">
              <el-radio
                v-for="item in levelOptions"
                :key="item.label"
                :value="item.label"
                :label="item.value">
                {{item.label}} ({{item.scone}})
              </el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
      </el-table>
      <div style="float: right; margin: 15px 3px;">
        <span style="margin: 4px 10px; font-size: 16px; font-weight: 700;">
          <span>总分：</span>
          <span>{{ totalScore }}</span>
        </span>
        <span style="margin: 4px 10px; font-size: 16px; font-weight: 700;">
          <span>已打分：</span>
          <!-- <span>{{ sumData.toFixed(2) }}</span> -->
          <span>{{ sumData }}</span>
        </span>
        <span style="margin: 4px 10px; font-size: 16px; font-weight: 700;">
          <span>剩余分数：</span>
          <span>{{ surplusSore }}</span>
        </span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchDanfenVisible = false">取消</el-button>
        <el-button type="primary" @click="batchFormSubmit()">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import axios from 'axios'
  import { Encrypt } from '../../utils/cryptoAES.js'
  import { AesDecrypt } from '../../utils/AesDecrypt.js'
  import store from '@/store'

  export default {

    data() {
      return {
        deptList: [],
        visible: false,
        visibleInfo: false,
        tableData: [],
        loadingPage: true,
        loading: true,
        currentPage: 0,
        page: 1,
        pageSize: 10,
        total: 0,
        checkedArr: [],//要导出的数据数组
        searchForm: {
          status: null,
          deptId: null,
          userId: null,//新人员编号
          userName: null,//名称
          dateInterval: []
        },
        optionsStates: [{
          value: null,
          label: '全部'
        }, {
          value: 0,
          label: '未提交'
        }, {
          value: 1,
          label: '已提交'
        }, {
          value: 2,
          label: '已驳回'
        }, {
          value: 3,
          label: '已申诉'
        }, {
          value: 4,
          label: '已同意'
        }
        ],
        // 批量打分
        batchDanfenVisible: false,
        // 打分
        danfenVisible: false,
        dafenForm: {
          id: '',
          performancePoint: 0,//部门绩效考核得分
          level: 0//员工绩效等级

        },

        levelOptions: [
          {
            value: 1,
            label: 'A+',
            scone: 1.08
          },
          {
            value: 2,
            label: 'A',
            scone: 1.05
          },
          {
            value: 3,
            label: 'B+',
            scone: 1.02
          },
          {
            value: 4,
            label: 'B',
            scone: 1
          },
          {
            value: 5,
            label: 'B-',
            scone: 0.95
          },
          {
            value: 6,
            label: 'C',
            scone: 0.9
          },
          {
            value: 7,
            label: 'D',
            scone: 0.5
          }
        ],
        dafenRule: {
          level: [
            { required: true, message: '员工绩效等级不能为空', trigger: 'blur' }
          ]
        },
        levelForm: {
          canAllocationAAdd: 0,
          canAllocationA: 0,
          canAllocationBAdd: 0,
          canAllocationC: 0,
          canAllocationB: null,
          canAllocationD: null
        },

        // 申诉
        sensuForm: {
          appraisalId: '',
          appealUser: '',
          deptId: '',
          deptName: '',
          contactNumber: '',
          description: ''
        },
        value: '',
        tableList: [],
        arrList: [],
        sumData: '',
        options: [
          {
            value: 0,
            label: '类型1'
          },
          {
            value: 1,
            label: '类型2'
          }
        ],
        // 申诉校验
        sensuRule: {
          appealUser: [
            { required: true, message: '申诉人不能为空', trigger: 'blur' }
          ],
          contactNumber: [
            { required: true, message: '联系方式不能为空', trigger: 'blur' }
          ],
          description: [
            { required: true, message: '申诉描述不能为空', trigger: 'blur' }
          ]
        },
        totalScore: '',
        surplusSore: ''
      }
    },
    created() {
      this.getUsersDept ()
      this.getDeptList ()

    },
    methods: {

      checkSubmit() {
        if (this.tableData.length > 0) {
          if (this.tableData[0].state === 0) {
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      },
      checkAppealSubmit() {
        if (this.tableData.length > 0) {
          if (this.tableData[0].state === 2) {
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      },
      // 获取列表
      async getList() {
        if (this.searchForm.dateInterval.length === 2) {
          this.searchForm.startTime = this.searchForm.dateInterval[0]
          this.searchForm.endTime = this.searchForm.dateInterval[1]
        }
        var uu = {
          page: this.page,
          pageSize: this.pageSize,
          status: this.searchForm.status,
          deptId: this.searchForm.deptId,//部门
          userId: this.searchForm.userId,//新人员编号
          userName: this.searchForm.userName,//名称
          startTime: this.searchForm.startTime,//开始时间
          endTime: this.searchForm.endTime//结束时间
        }
        console.log (this.searchForm.deptId)
        var jsonString = JSON.stringify (uu)
        var yy = Encrypt (jsonString)
        var encodedString = encodeURIComponent (yy)
        axios ({
          method: 'post',
          url: '/hr-xc-human-resources-perform-manage/generator/performanceappraisal/list',
          data: encodedString
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            var data = AesDecrypt (data.result)
            this.tableData = data.content
            this.total = data.total
            this.loading = false
            this.loadingPage = false
          } else {
            this.loading = false
            this.loadingPage = false
            this.$message.error (data.msg)
            this.tableData = []
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },
      // 总分
      getTotalPoints() {
        let date = new Date ()
        let year = date.getFullYear () // 获取当前年份
        let month = date.getMonth () + 1 // 获取当前月份。注意，月份是从0开始的，所以需要加1
        month = month < 10 ? '0' + month : month // 如果月份小于10，前面补0
        var uu = {
          page: this.page,
          pageSize: this.pageSize,
          deptId: this.searchForm.deptId,//部门ID
          state: '0',//绩效管理委员会默认只查看已提交的
          createTime: year + '-' + month
        }
        console.log (this.searchForm.deptId)
        var jsonString = JSON.stringify (uu)
        var yy = Encrypt (jsonString)
        var encodedString = encodeURIComponent (yy)
        axios ({
          method: 'post',
          url: '/hr-xc-human-resources-perform-manage/generator/performanceoffice/list',
          data: encodedString
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            var data = AesDecrypt (data.result)
            data.result.content.map (item => {
              this.totalScore = item.totalScore
            })
            this.surplusSore = this.totalScore - this.sumData
            let strNum = this.surplusSore.toString ()
            let decimalIndex = strNum.indexOf ('.')
            this.surplusSore = strNum.slice (0, decimalIndex + 3)
            console.log (this.totalScore, this.surplusSore)
            // this.tableData = data.result.content
            // this.total = data.result.total
            this.loading = false
            this.loading = false
            this.loadingPage = false
          } else {
            this.loading = false
            this.loadingPage = false
            this.$message.error (data.msg)
            this.tableData = []
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },

      // 查询
      searchBtn() {
        this.loading = true
        this.page = 1
        this.getUsersDept ()
      },
      /** 点击分页触发的事件 */
      handlePageChange(pageInfo) {
        this.loading = true
        this.page = pageInfo.page
        this.pageSize = pageInfo.limit
        this.getList ()

      },
// 导出
      async exportForm() {
        this.loadingPage = true
        this.searchForm.ids = []
        if (this.checkedArr.length != 0) {
          this.checkedArr.forEach (item => {
            this.searchForm.ids.push (item.id)
          })
        } else {
          this.searchForm.ids = []
        }
        axios ({
          method: 'post',
          responseType: 'blob',
          url: '/hr-xc-human-resources-perform-manage/generator/performanceappraisal/export',
          data: {
            ids: this.searchForm.ids,
            status: this.searchForm.status,
            deptId: this.searchForm.deptId,//部门
            userId: this.searchForm.userId,//新人员编号
            userName: this.searchForm.userName,//名称
            startTime: this.searchForm.startTime,//开始时间
            endTime: this.searchForm.endTime//结束时间
          }
        }).then (({ data }) => {
          if (data.size) {
            const downloadElement = document.createElement ('a')
            const href = window.URL.createObjectURL (data) // 创建下载的链接
            downloadElement.href = href
            downloadElement.download = decodeURI ('绩效考核.xls') // 下载后文件名
            document.body.appendChild (downloadElement)
            downloadElement.click () // 点击下载
            document.body.removeChild (downloadElement) // 下载完成移除元素
            window.URL.revokeObjectURL (href) // 释放掉blob对象
            this.loadingPage = false
            // this.$my_message.success ('导出成功')
            this.$message.success ('导出成功')
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },

      // 清空
      emptyClick() {
        this.searchForm.userId = null,//新人员编号
          this.searchForm.userName = null,//名称
          this.searchForm.status = null,
          this.searchForm.dateInterval = []
      },

      bindRowKeys(row) {
        return row.id
      },
      // 多选
      handleSelectionChange(value) {
        this.checkedArr = value
        // element表格多选第一页选中往后翻一页全选，再回到第一页会再次选中第一页的数据，所以需要手动去重
        let hash = {}
        this.checkedArr = this.checkedArr.reduce ((preVal, curVal) => {
          hash[curVal.id] ? '' : hash[curVal.id] = true && preVal.push (curVal)
          return preVal
        }, [])
      },

      // 提交
      submit() {
        axios ({
          method: 'post',
          url: '/hr-xc-human-resources-perform-manage/generator/performanceappraisal/submitTo',
          data: {
            deptId: this.searchForm.deptId//部门
          }
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            if (data.result.result) {
              this.$message ({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.refresh ()
                }
              })
            } else {
              this.$message.error (data.result.message)
            }
          } else {
            this.loading = false
            this.loadingPage = false
            this.$message.error (data.result.message)
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })

      },
      // // 申诉
      appealSubmit(row) {
        this.visible = true
        this.getUsersDept ()
      },
      selectable(row, index) {
        if (row.state === 0 || row.state === 4) {
          return true
        } else {
          return false
        }
      },
      sensuFormSubmit() {
        this.$refs['sensuForm'].validate ((valid) => {
          if (valid) {
            var uu = {
              appraisalId: this.sensuForm.appraisalId,
              appealUser: this.sensuForm.appealUser,
              appealType: this.sensuForm.appealType,
              contactNumber: this.sensuForm.contactNumber,
              description: this.sensuForm.description,
              deptId: this.searchForm.deptId,
              deptName: this.sensuForm.deptName
            }
            var jsonString = JSON.stringify (uu)
            var yy = Encrypt (jsonString)
            var encodedString = encodeURIComponent (yy)

            axios ({
              method: 'post',
              url: '/hr-xc-human-resources-perform-manage/generator/performanceappraisal/appeal',
              data: encodedString
            }).then (({ data }) => {
              if (data && data.code === '00000') {
                this.$message ({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.getUsersDept ()
                  }
                })
              } else {
                return this.$message.warning (data.message)
              }
            }).catch (error => {
              this.$message.error ('服务器访问异常，请从新登录')
            })
          }
        })
      },
      // 批量打分
      batchHandleDafen() {
        this.batchDanfenVisible = true
        var uu = {
          status: this.searchForm.status,
          deptId: this.searchForm.deptId,//部门
          userId: this.searchForm.userId,//新人员编号
          userName: this.searchForm.userName,//名称
          startTime: this.searchForm.startTime,//开始时间
          endTime: this.searchForm.endTime//结束时间
        }
        var jsonString = JSON.stringify (uu)
        var yy = Encrypt (jsonString)
        var encodedString = encodeURIComponent (yy)
        axios ({
          method: 'post',
          url: `/hr-xc-human-resources-perform-manage/generator/performanceappraisal/scoringList`,
          data: encodedString
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            var data = AesDecrypt (data.result)
            this.tableList = data
            console.log ('this.tableList', this.tableList)
            let arr = []
            this.tableList.map (item => {
              arr.push (item.performancePoint)
            })
            let sum = arr.reduce ((accumulator, currentValue) => accumulator + currentValue, 0)
            this.sumData = sum
            let strNum = sum.toString ()
            let decimalIndex = strNum.indexOf ('.')
            this.sumData = strNum.slice (0, decimalIndex + 3)
            this.getTotalPoints ()
          }
        })
          .catch (error => {
            // this.$message.error ('服务器访问异常，请从新登录')
          })

      },
      // 单条得分提交
      formSubmit() {
        axios ({
          method: 'post',
          url: '/hr-xc-human-resources-perform-manage/generator/performanceappraisal/scoreAndRate',
          data: {
            id: this.dafenForm.id,
            performancePoint: this.dafenForm.performancePoint,
            level: this.dafenForm.level
          }
        }).then (({ data }) => {
            if (data && data.code === '00000') {
              if (data.result === 1) {
                this.$message ({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.danfenVisible = false
                    this.getUsersDept ()
                  }
                })
              } else {
                this.$message.error ('打分失败')
              }
            }
          }
        ).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },
      // 批量得分提交
      batchFormSubmit() {
        // 将数组转换为 JSON 字符串
        var jsonData = JSON.stringify (this.tableList)
        var yy = Encrypt (jsonData)
        var encodedString = encodeURIComponent (yy)
        axios ({
          method: 'post',
          url: '/hr-xc-human-resources-perform-manage/generator/performanceappraisal/scoreAndRateBatch',
          data: encodedString
        }).then (({ data }) => {
            if (data && data.code === '00000') {
              if (data.result === true) {
                this.$message ({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.batchDanfenVisible = false
                    this.getUsersDept ()
                  }
                })
              } else {
                this.$message.error ('打分失败')
              }
            }
          }
        ).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },
      // 获得当前登录人
      getUsersDept() {
        const userCode = store.state.userCode
        axios ({
          url: `/hr-xc-human-resources-perform-manage/generator/performanceappraisal/queryDeptCodeByUserCode/${userCode}`,
          method: 'get'
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            var data = AesDecrypt (data.result)
            this.sensuForm.appealUser = data.userName
            this.searchForm.deptId = data.depId
            this.getList ()
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },

      // 刷新
      refresh() {
        this.getUsersDept ()
      },
      getDeptList() {
        axios ({
          method: 'post',
          url: '/hr-xc-human-resources-perform-manage/generator/torgdept/queryAllDeptIdAndName'
        }).then (({ data }) => {
          if (data && data.code === '00000') {
            var data = AesDecrypt (data.result)
            this.deptList = data
          }
        }).catch (error => {
          this.$message.error ('服务器访问异常，请从新登录')
        })
      },
      levelChange(val) {
        this.dafenForm.level = val
        let dir = this.levelOptions.find ((item) => item.value === val)
        this.dafenForm.performancePoint = dir.scone
      },
      batchLevelChange(val, row, index) {
        let dir = this.levelOptions.find ((item) => item.value === val)
        this.tableList.forEach (v => {
          if (v.id == row.id) {
            v.performancePoint = dir.scone
            v.level = val
          }
        })
        let arr = []
        this.tableList.map (item => {
          arr.push (item.performancePoint)
        })
        let sum = arr.reduce ((accumulator, currentValue) => accumulator + currentValue, 0)
        let strNum = sum.toString ()
        let decimalIndex = strNum.indexOf ('.')
        this.sumData = strNum.slice (0, decimalIndex + 3)
        let newNum = null
        newNum = Number (this.totalScore) - Number (this.sumData)
        let strNum1 = newNum.toString ()
        let decimalIndex1 = strNum1.indexOf ('.')
        this.surplusSore = strNum1.slice (0, decimalIndex1 + 3)
      }
    }
  }
</script>
<style>
  .dialog-custom {

  .el-dialog {
    /* width: auto !important ; 设置宽度为自适应   */
    width: 75vw !important;
  }

  }
  .item {
    margin-top: 10px;
    margin-right: 40px;
  }
</style>
